package bigbeard.tools.net.server.impl;


import bigbeard.tools.net.server.BaseConnector;
import bigbeard.tools.net.utils.Utils;

import java.nio.channels.SocketChannel;
import java.nio.charset.StandardCharsets;

/**
 * @author bigbeard on 2022-09-29
 */
public class TcpSocketConnectorImpl extends BaseConnector {

    private SocketChannel clientChannel;


    @Override
    public int send(String message) throws Exception {
        if (null != this.clientChannel && this.clientChannel.isOpen()) {
            byte[] bytes = message.getBytes(StandardCharsets.UTF_8);
            return this.send(bytes);
        }
        return SEND_ERROR;
    }

    @Override
    public int send(byte[] message) throws Exception {
        if (null != this.clientChannel && this.clientChannel.isOpen()) {
            int write = Utils.write(this.clientChannel, message);
            if (write > 0) {
                this.updateLastMsgTime();
            }
            return write;
        }
        return SEND_ERROR;
    }


    @Override
    public void setConnector(Object client) {
        if (client instanceof SocketChannel) {
            this.clientChannel = (SocketChannel) client;
        }
    }

    @Override
    public void close() {
        if (null != this.clientChannel) {
            try {
                this.clientChannel.close();
            } catch (Exception ignored) {
            }
            this.clientChannel = null;
        }
    }
}
